package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;

import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.pojo.OrderDetail;
import com.itheima.reggie.pojo.Orders;
import com.itheima.reggie.pojo.ShoppingCart;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        //先存order表,一个用户id同一时间只能对应一个order订单
        log.info("orders:{}",orders); //addressBookId ,payMethod ,remark
        Orders orderNeed = new Orders();
        BeanUtils.copyProperties(orders,orderNeed);
        orderNeed.setStatus(1);        //status订单状态
        orderNeed.setUserId(BaseContext.getThreadId());    //user_id 下单用户
        orderNeed.setOrderTime(LocalDateTime.now());       //order_time 下单时间
        orderNeed.setCheckoutTime(LocalDateTime.now());    //checkout_time 结账时间
        orderNeed.setNumber(String.valueOf(IdWorker.getId()));
        //查询所有购物车,获取订单总金额,订单支付后,购物车信息全部删除
        List<ShoppingCart> list = shoppingCartService.list();
        BigDecimal sum = BigDecimal.ZERO;
        for (ShoppingCart shoppingCart : list) {
            BigDecimal amount = shoppingCart.getAmount();
            Integer number = shoppingCart.getNumber();
            BigDecimal decimalNumber = BigDecimal.valueOf(number);
            BigDecimal multiplyNumber = amount.multiply(decimalNumber);
            sum = sum.add(multiplyNumber);
        }
        orderNeed.setAmount(sum);      //总金额--查询shopping_cart,得到集合,遍历集合相加
        //数据填充完成,保存orderNeed
        orderService.save(orderNeed);



        //保存order_detail表
        Long orderId = orderNeed.getId();   //order_id  订单id

        list.forEach(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orderId);
            //保存orderDetail
            orderDetailService.save(orderDetail);
        });

        //清空订单表
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId,BaseContext.getThreadId());
        shoppingCartService.remove(qw);
        return R.success("支付成功");
    }

    //分页查询订单列表
    @GetMapping("userPage")
    public R<Page<OrderDto>> orderPage(int page, int pageSize){
        log.info("page:{},pageSize:{}",page,pageSize);
        Page<OrderDto> orderDtoPage = new Page<>();

        //构建分页构造器
        Page<Orders> ordersPage = new Page<>(page, pageSize);

        //1.1orderPage赋值非records部分
        BeanUtils.copyProperties(ordersPage,orderDtoPage,"records");

        //构造查询条件构造器
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(Orders::getUserId,BaseContext.getThreadId());
        orderService.page(ordersPage, qw);
        //2.1List<OrderDto>赋值order部分
        List<OrderDto> orderDtoList = new ArrayList<>();
        ordersPage.getRecords().forEach(order -> {
            OrderDto orderDto = new OrderDto();
            //2.21List<OrderDto> 赋值List<OrderDetail>部分
            BeanUtils.copyProperties(order,orderDto);

            Long orderId = order.getId();
            LambdaQueryWrapper<OrderDetail> orderqw = new LambdaQueryWrapper<>();
            orderqw.eq(OrderDetail::getOrderId, orderId);
            List<OrderDetail> list = orderDetailService.list(orderqw);
            //赋值2,赋值List<OrderDetail>部分
            orderDto.setOrderDetails(list);
            orderDtoList.add(orderDto);
        });

        //1.2 orderDtoPage赋值records部分
        orderDtoPage.setRecords(orderDtoList);
        return R.success(orderDtoPage);


    }

}
